#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <error.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <fcntl.h>
#define PORT 8888
#define SERVER_IP "0.0.0.0"
#define LISTEN_BYTES 128
#define MASSAGE_SIZE 64
#define EVENT_SIZE 128
typedef struct FD_SET
{
    int acceptfd;
    int epfd;
} FD_SET;

static void *worker_func(void *arg)
{
    pthread_detach(pthread_self());
    FD_SET fdSet = *(FD_SET *)arg;
    /*接收信息*/
    char recMessage[MASSAGE_SIZE];
    memset(recMessage, 0, sizeof(recMessage));
    /*发送信息*/
    char sendMessage[MASSAGE_SIZE];
    memset(sendMessage, 0, sizeof(sendMessage));
    strncpy(sendMessage, "456", sizeof(sendMessage) - 1);

    struct epoll_event acceptEvent;
    memset(&acceptEvent, 0, sizeof(acceptEvent));
    acceptEvent.events = EPOLLIN;
    acceptEvent.data.fd = fdSet.acceptfd;
    int ret = 0;
    int readBytes = 0;
    while (1)
    {
        /*第五步：通信*/

        /*读取客户端发送的信息*/
        readBytes = read(fdSet.acceptfd, recMessage, sizeof(recMessage) - 1);
        if (readBytes < 0)
        {
            perror("read error");
            ret = epoll_ctl(fdSet.epfd, EPOLL_CTL_DEL, fdSet.acceptfd, &acceptEvent);
            if (ret == -1)
            {
                perror("epoll_ctl1 error");
            }
            close(fdSet.acceptfd);
            break;
        }
        else if (readBytes == 0)
        {
            ret = epoll_ctl(fdSet.epfd, EPOLL_CTL_DEL, fdSet.acceptfd, &acceptEvent);
            if (ret == -1)
            {
                printf("客户端下线......\n");
            }
            close(fdSet.acceptfd);
            break;
        }
        else
        {
            /*通信*/
            printf("client massage=%s\n", recMessage);
        }
    }

    pthread_exit(NULL);
}
int main()
{
    /*构建服务器的步骤*/
    /*第一步：socket：创建套接字*/
    /*三个参数:协议(ipv4/ipv6),SOCK_STREAM/SOCK_DGRAM(tcp/udp),默认0*/
    /*返回值：文件描述符*/
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket error");
        exit(-1);
    }
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    /*inet_pton函数的三个参数：协议(ipv4/ipv6),IP,写入的地址(传出参数)*/
    int ret = inet_pton(AF_INET, SERVER_IP, (void *)&serverAddr.sin_addr.s_addr);
    if (ret == -1)
    {
        perror("inet_pton error");
        exit(-1);
    }
    /*第二步:bind绑定本地信息*/
    /*bind三个参数：sockfd;sockaddr_in结构体包括：协议(ipv4/ipv6)，IP,端口;sizeof（第二个参数）*/

    int opt = 1;
    /*在进行bind函数前进行端口复用选择*/
    /*setsockopt函数5个参数：sockfd；SOL_SOCKET;SO_REUSEADDR;opt=1(复用)/0(不复用);第四个参数大小*/
    ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&opt, sizeof(opt));
    if (ret == -1)
    {
        perror("setsockopt error");
        exit(-1);
    }
    ret = bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
    if (ret == -1)
    {
        perror("bind error");
        exit(-1);
    }
    /*第三步：listen监听连接*/
    /*listen两个参数：sockfd;监听字节数*/
    listen(sockfd, LISTEN_BYTES);

    /*第四步：accept函数，接收客户端的连接*/
    /*accept三个参数:sockfd;客户端信息(传出参数)：ip，端口，协议；socklen_t类型的(传出参数)*/
    /*返回连接套接字：用于通信*/
    struct sockaddr_in clientAddr;
    memset(&clientAddr, 0, sizeof(clientAddr));
    socklen_t clientAddrSize;

    int epfd = epoll_create(0);
    if (epfd == -1)
    {
        perror("epoll_create error");
        exit(-1);
    }
    struct epoll_event event;
    memset(&event, 0, sizeof(event));
    event.events = EPOLLIN;
    event.data.fd = sockfd;
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &event);
    if (ret == -1)
    {
        perror("epoll_ctl2 error");
        exit(-1);
    }
    int acceptfd = 0;

    FD_SET fdSet;
    memset(&fdSet, 0, sizeof(fdSet));
    while (1)
    {
        struct epoll_event waitEvent[EVENT_SIZE];
        memset(waitEvent, 0, sizeof(waitEvent));
        /*监听sockfd,waitEvent中是发生读事件的文件描述符*/
        ret = epoll_wait(epfd, waitEvent, EVENT_SIZE, -1);
        if (ret == -1)
        {
            perror("epoll_wait error");
            exit(-1);
        }

        for (int idx = 0; idx < EVENT_SIZE; idx++)
        {
            int fd = waitEvent->data.fd;
            if (fd == sockfd)
            {
                fcntl()
                    acceptfd = accept(fd, NULL, NULL);

                if (acceptfd == -1)
                {
                    perror("accept error");
                    close(fd);
                    continue;
                }

                struct epoll_event acceptEvent;
                memset(&acceptEvent, 0, sizeof(acceptEvent));
                acceptEvent.data.fd = fd;
                acceptEvent.events = EPOLLIN;
                epoll_ctl(epfd, EPOLL_CTL_ADD, acceptfd, &acceptEvent);
            }
            else
            {
                fdSet.acceptfd = fd;
                fdSet.epfd = epfd;
                /*通信*/
                pthread_t tid;
                pthread_create(&tid, NULL, worker_func, &fdSet);
            }
        }
    }

    sleep(2);
    /*第七步：关闭*/

    close(sockfd);
    return 0;
}